#include <QRegExp>
#include <QDebug>
#include <QList>
#include <QString>

#include "httpparser.h"
#include "parserglobals.h"


HttpParser::HttpParser( QList< const QString* >* list, QObject* parent ):QObject(parent), m_progress( 0 )
{
	if( list )
		m_items = *list;
}

HttpParser::~HttpParser()
{
	while( !m_customParsers.isEmpty( ))
		delete m_customParsers.takeFirst();
	
	m_items.clear();

}

void HttpParser::parse()
{
	QString result;
	m_progress = 0;
	m_total = 0;

	UrlList::iterator it = m_items.begin();

	while( it != m_items.end() )
	//foreach( const QString* const desc, m_items )
	{
		if( rapidshareLink( *(*it), result ))
		{
			emit(linkParsed( result ));
		}
		else if( uploadJockey( *(*it), result ))
		{
			//TODO: create customparser object and trigger on fetching content from parsed url
			QUrl url( result );
			if( url.isValid( ))
			{
				//custom parser will handle the result and return back here.
				CustomParser* parser = new CustomParser( url, this, this );
				m_customParsers.append( parser );
				connect( parser, SIGNAL( linkParsed( const QString&, CustomParser* )), this, SLOT( parsed( const QString&, CustomParser* )));
				connect( parser, SIGNAL( parseErr( int, CustomParser* )), this, SLOT( parsingError( int, CustomParser* )));
				connect( parser, SIGNAL( progress( int )), this, SLOT( progress( int )));
			}
			else
				qDebug() << "imvalid link parsed";
		}
	++it;
	}
}

void HttpParser::parse( UrlList list )
{
	m_items.clear();
	m_items = list;
	m_total = m_items.count() * 100;
	parse();
}

void HttpParser::parsed( const QString& url, CustomParser* parser )
{
	emit( linkParsed( url ));
	int ind = m_customParsers.indexOf( parser );
	m_customParsers.removeAt( ind );
	delete parser;

	if( m_customParsers.isEmpty() )
		qDebug() << "FINISHED";
}


void HttpParser::parsingError( int error, CustomParser* parser )
{
	int ind = m_customParsers.indexOf( parser );
	m_customParsers.removeAt( ind );
	delete parser;

	if( m_customParsers.isEmpty() )
		qDebug() << "FINISHED";
}

void HttpParser::progress( int progress )
{
	m_progress += progress;
	qDebug() << m_progress / m_total << "%%%%%%";
}

//eof
